package com.itheima.package1_threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Demo3_ThreadPoolExecutor {
    public static void main(String[] args) {
        /*自定义线程池
        public ThreadPoolExecutor​(int corePoolSize,核心线程数
            int maximumPoolSize,最大线程数
            long keepAliveTime,空闲线程最大存活时间
            TimeUnit unit,时间单位
            BlockingQueue<Runnable> workQueue,任务队列
            ThreadFactory threadFactory,创建线程的工厂
            RejectedExecutionHandler handler任务的拒绝策略)

        1/首先使用核心线
        2/同时提交的任务超出了核心线程数量,进入阻塞队列
        3/同时提交的任务超出了核心线程数量,阻塞队列数量,创建临时线程执行
        4/如果超出了线程池容量+阻塞队列,触发拒绝策略
        5/四种拒绝策略
        ThreadPoolExecutor.AbortPolicy--拒绝任务并抛出异常
        ThreadPoolExecutor.DiscardPolicy--拒绝任务,不抛出异常/不建议使用
        ThreadPoolExecutor.DiscardOldestPolicy--丢弃等待时间最长的任务
        ThreadPoolExecutor.CallerRunsPolicy--绕过线程,直接去调用run方法*/
        ThreadPoolExecutor pool= new ThreadPoolExecutor(
                2,
                5,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()//丢弃多余的抛出异常
                );
        for (int i = 0; i < 15; i++) {
            pool.submit(()-> System.out.println(Thread.currentThread().getName()+"开始了"));
        }
    }
}
